import express, { Request, Response, Router } from 'express';
import { RoomService } from '../models/Room';
import {puppeteerManager} from '../puppeteer-service';
import fs from 'fs';
import path from 'path';
import { LiveStreamManager } from '../LiveStreamManager';

const router: Router = express.Router();
const roomService = new RoomService();



// 创建房间
router.post('/', async (req: Request, res: Response) => {
  try {
    const { id } = req.body;

    if (!id) {
      res.status(400).json({ error: '房间ID/主播主页/sec_uid不能为空' });
      return;
    }

    // getLiveInfo 现在支持多种输入方式（房间号、主播主页URL、sec_uid等）
    const info = await puppeteerManager.getLiveInfo(id);
    const { roomId, title, cover, nickname: name, avatar } = info;

    // 使用解析出来的 roomId 创建房间
    const room = await roomService.upsertRoom(
      roomId,
      title,
      cover,
      name,
      avatar,
    );

    // 处理upsert返回值（可能是数组或单个对象）
    const roomModel: any = Array.isArray(room) ? room[0] : room;
    const base = typeof roomModel?.toJSON === 'function' ? roomModel.toJSON() : roomModel;

    // 获取录制状态
    const snapshot = LiveStreamManager.snapshot();
    const session = snapshot.find(s => s.roomId === roomId);
    const danmuActive = session !== undefined;
    const videoActive = session?.isRecording === true;
    res.json({ success: true, data: { ...base, isVideoRecording: videoActive, isDanmuRecording: danmuActive } });
  } catch (error) {
    console.error('创建房间失败:', error);
    res.status(500).json({ error: '创建房间失败' });
  }
});

 

// 获取房间信息（附带 isDanmuRecording / isVideoRecording）
router.get('/:id', async (req: Request, res: Response) => {
  try {
    const { id } = req.params;
    const room = await roomService.getRoom(id);

    if (!room) {
      res.status(404).json({ error: '房间不存在' });
      return;
    }

    // 处理room对象，确保可以调用toJSON
    const base = typeof (room as any)?.toJSON === 'function' ? (room as any).toJSON() : room;

    // 获取录制状态
    const snapshot = LiveStreamManager.snapshot();
    const session = snapshot.find(s => s.roomId === id);
    const danmuActive = session !== undefined;
    const videoActive = session?.isRecording === true;
    res.json({ success: true, data: { ...base, isVideoRecording: videoActive, isDanmuRecording: danmuActive } });
  } catch (error) {
    console.error('获取房间信息失败:', error);
    res.status(500).json({ error: '获取房间信息失败' });
  }
});

// 更新房间信息
router.put('/:id', async (req: Request, res: Response) => {
  try {
    const { id } = req.params;
    const { 
      title, 
      coverUrl, 
      streamerName, 
      streamerAvatar, 
      streamerDisplayId, 
      streamerShortId,
      type,
      weight
    } = req.body;
    
    const room = await roomService.upsertRoom(
      id, 
      title, 
      coverUrl, 
      streamerName, 
      streamerAvatar, 
      streamerDisplayId, 
      streamerShortId,
      type,
      weight
    );
    res.json({ success: true, data: room });
  } catch (error) {
    console.error('更新房间信息失败:', error);
    res.status(500).json({ error: '更新房间信息失败' });
  }
});

// 删除房间
router.delete('/:id', async (req: Request, res: Response) => {
  try {
    const { id } = req.params;
    
    // 检查房间是否存在
    const existingRoom = await roomService.getRoom(id);
    if (!existingRoom) {
      res.status(404).json({ error: '房间不存在' });
      return;
    }
    
    // 删除房间（注意：这会级联删除相关的sessions、messages等）
    await roomService.deleteRoom(id);
    res.json({ success: true, message: '房间删除成功' });
  } catch (error) {
    console.error('删除房间失败:', error);
    res.status(500).json({ error: '删除房间失败' });
  }
});

// 获取所有房间列表（附带 isDanmuRecording / isVideoRecording）
router.get('/', async (req: Request, res: Response) => {
  try {
    const { page = 1, limit = 30 } = req.query;
    const result = await roomService.getRooms(Number(page), Number(limit));

    const snapshot = LiveStreamManager.snapshot();
    const sessionMap = new Map(snapshot.map(s => [s.roomId, s]));

    const rooms = result.rooms.map((r: any) => {
      const session = sessionMap.get(r.id);
      const danmuActive = session !== undefined; // session存在即为弹幕录制
      const videoActive = session?.isRecording === true; // isRecording为true即为视频录制
      return { ...r.toJSON(), isVideoRecording: videoActive, isDanmuRecording: danmuActive };
    });
    res.json({ success: true, data: { ...result, rooms } });
  } catch (error) {
    console.error('获取房间列表失败:', error);
    res.status(500).json({ error: '获取房间列表失败' });
  }
});


export default router;
